home *** CD-ROM | disk | FTP | other *** search
/ Language/OS - Multiplatform Resource Library / LANGUAGE OS.iso / lisp / kcl / akcl / akcl1615.lha / c / gnumalloc.c < prev    next >
C/C++ Source or Header  |  1989-10-24  |  24KB  |  817 lines

  1. /* dynamic memory allocation for GNU.
  2.    Copyright (C) 1985, 1987 Free Software Foundation, Inc.
  3.  
  4.                NO WARRANTY
  5.  
  6.   BECAUSE THIS PROGRAM IS LICENSED FREE OF CHARGE, WE PROVIDE ABSOLUTELY
  7. NO WARRANTY, TO THE EXTENT PERMITTED BY APPLICABLE STATE LAW.  EXCEPT
  8. WHEN OTHERWISE STATED IN WRITING, FREE SOFTWARE FOUNDATION, INC,
  9. RICHARD M. STALLMAN AND/OR OTHER PARTIES PROVIDE THIS PROGRAM "AS IS"
  10. WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
  11. BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  12. FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY
  13. AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE PROGRAM PROVE
  14. DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR
  15. CORRECTION.
  16.  
  17.  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW WILL RICHARD M.
  18. STALLMAN, THE FREE SOFTWARE FOUNDATION, INC., AND/OR ANY OTHER PARTY
  19. WHO MAY MODIFY AND REDISTRIBUTE THIS PROGRAM AS PERMITTED BELOW, BE
  20. LIABLE TO YOU FOR DAMAGES, INCLUDING ANY LOST PROFITS, LOST MONIES, OR
  21. OTHER SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
  22. USE OR INABILITY TO USE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR
  23. DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY THIRD PARTIES OR
  24. A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS) THIS
  25. PROGRAM, EVEN IF YOU HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH
  26. DAMAGES, OR FOR ANY CLAIM BY ANY OTHER PARTY.
  27.  
  28.         GENERAL PUBLIC LICENSE TO COPY
  29.  
  30.   1. You may copy and distribute verbatim copies of this source file
  31. as you receive it, in any medium, provided that you conspicuously and
  32. appropriately publish on each copy a valid copyright notice "Copyright
  33. (C) 1985 Free Software Foundation, Inc."; and include following the
  34. copyright notice a verbatim copy of the above disclaimer of warranty
  35. and of this License.  You may charge a distribution fee for the
  36. physical act of transferring a copy.
  37.  
  38.   2. You may modify your copy or copies of this source file or
  39. any portion of it, and copy and distribute such modifications under
  40. the terms of Paragraph 1 above, provided that you also do the following:
  41.  
  42.     a) cause the modified files to carry prominent notices stating
  43.     that you changed the files and the date of any change; and
  44.  
  45.     b) cause the whole of any work that you distribute or publish,
  46.     that in whole or in part contains or is a derivative of this
  47.     program or any part thereof, to be licensed at no charge to all
  48.     third parties on terms identical to those contained in this
  49.     License Agreement (except that you may choose to grant more extensive
  50.     warranty protection to some or all third parties, at your option).
  51.  
  52.     c) You may charge a distribution fee for the physical act of
  53.     transferring a copy, and you may at your option offer warranty
  54.     protection in exchange for a fee.
  55.  
  56. Mere aggregation of another unrelated program with this program (or its
  57. derivative) on a volume of a storage or distribution medium does not bring
  58. the other program under the scope of these terms.
  59.  
  60.   3. You may copy and distribute this program (or a portion or derivative
  61. of it, under Paragraph 2) in object code or executable form under the terms
  62. of Paragraphs 1 and 2 above provided that you also do one of the following:
  63.  
  64.     a) accompany it with the complete corresponding machine-readable
  65.     source code, which must be distributed under the terms of
  66.     Paragraphs 1 and 2 above; or,
  67.  
  68.     b) accompany it with a written offer, valid for at least three
  69.     years, to give any third party free (except for a nominal
  70.     shipping charge) a complete machine-readable copy of the
  71.     corresponding source code, to be distributed under the terms of
  72.     Paragraphs 1 and 2 above; or,
  73.  
  74.     c) accompany it with the information you received as to where the
  75.     corresponding source code may be obtained.  (This alternative is
  76.     allowed only for noncommercial distribution and only if you
  77.     received the program in object code or executable form alone.)
  78.  
  79. For an executable file, complete source code means all the source code for
  80. all modules it contains; but, as a special exception, it need not include
  81. source code for modules which are standard libraries that accompany the
  82. operating system on which the executable file runs.
  83.  
  84.   4. You may not copy, sublicense, distribute or transfer this program
  85. except as expressly provided under this License Agreement.  Any attempt
  86. otherwise to copy, sublicense, distribute or transfer this program is void and
  87. your rights to use the program under this License agreement shall be
  88. automatically terminated.  However, parties who have received computer
  89. software programs from you with this License Agreement will not have
  90. their licenses terminated so long as such parties remain in full compliance.
  91.  
  92.   5. If you wish to incorporate parts of this program into other free
  93. programs whose distribution conditions are different, write to the Free
  94. Software Foundation at 675 Mass Ave, Cambridge, MA 02139.  We have not yet
  95. worked out a simple rule that can be stated here, but we will often permit
  96. this.  We will be guided by the two goals of preserving the free status of
  97. all derivatives of our free software and of promoting the sharing and reuse of
  98. software.
  99.  
  100.  
  101. In other words, you are welcome to use, share and improve this program.
  102. You are forbidden to forbid anyone else to use, share and improve
  103. what you give them.   Help stamp out software-hoarding!  */
  104.  
  105.  
  106. /*
  107.  * @(#)nmalloc.c 1 (Caltech) 2/21/82
  108.  *
  109.  *    U of M Modified: 20 Jun 1983 ACT: strange hacks for Emacs
  110.  *
  111.  *    Nov 1983, Mike@BRL, Added support for 4.1C/4.2 BSD.
  112.  *
  113.  * This is a very fast storage allocator.  It allocates blocks of a small 
  114.  * number of different sizes, and keeps free lists of each size.  Blocks
  115.  * that don't exactly fit are passed up to the next larger size.  In this 
  116.  * implementation, the available sizes are (2^n)-4 (or -16) bytes long.
  117.  * This is designed for use in a program that uses vast quantities of
  118.  * memory, but bombs when it runs out.  To make it a little better, it
  119.  * warns the user when he starts to get near the end.
  120.  *
  121.  * June 84, ACT: modified rcheck code to check the range given to malloc,
  122.  * rather than the range determined by the 2-power used.
  123.  *
  124.  * Jan 85, RMS: calls malloc_warning to issue warning on nearly full.
  125.  * No longer Emacs-specific; can serve as all-purpose malloc for GNU.
  126.  * You should call malloc_init to reinitialize after loading dumped Emacs.
  127.  * Call malloc_stats to get info on memory stats if MSTATS turned on.
  128.  * realloc knows how to return same block given, just changing its size,
  129.  * if the power of 2 is correct.
  130.  */
  131.  
  132. /*
  133.  * nextf[i] is the pointer to the next free block of size 2^(i+3).  The
  134.  * smallest allocatable block is 8 bytes.  The overhead information will
  135.  * go in the first int of the block, and the returned pointer will point
  136.  * to the second.
  137.  *
  138. #ifdef MSTATS
  139.  * nmalloc[i] is the difference between the number of mallocs and frees
  140.  * for a given block size.
  141. #endif /* MSTATS */
  142.  
  143. #ifdef emacs
  144. #include "config.h"
  145. #endif /* emacs */
  146.  
  147. /* Determine which kind of system this is.  */
  148. #include <signal.h>
  149. #ifndef SIGTSTP
  150. #ifndef VMS
  151. #ifndef USG
  152. #define USG
  153. #endif
  154. #endif /* not VMS */
  155. #else /* SIGTSTP */
  156. #ifdef SIGIO
  157. #define BSD42
  158. #endif /* SIGIO */
  159. #endif /* SIGTSTP */
  160.  
  161. /* Define getpagesize () if the system does not.  */
  162. #include "getpagesize.h"
  163.  
  164. #ifndef BSD42
  165. #ifndef USG
  166. #include <sys/vlimit.h>        /* warn the user when near the end */
  167. #endif /* not USG */
  168. #else /* if BSD42 */
  169. #include <sys/time.h>
  170. #include <sys/resource.h>
  171. #endif /* BSD42 */
  172.  
  173. extern char *start_of_data ();
  174.  
  175. #ifdef BSD
  176. #ifndef DATA_SEG_BITS
  177. #define start_of_data() &etext
  178. #endif
  179. #endif
  180.  
  181. #ifndef emacs
  182. #define start_of_data() &etext
  183. #endif
  184.  
  185. #define ISALLOC ((char) 0xf7)    /* magic byte that implies allocation */
  186. #define ISFREE ((char) 0x54)    /* magic byte that implies free block */
  187.                 /* this is for error checking only */
  188. #define ISMEMALIGN ((char) 0xd6)  /* Stored before the value returned by
  189.                      memalign, with the rest of the word
  190.                      being the distance to the true
  191.                      beginning of the block.  */
  192.  
  193. extern char etext;
  194.  
  195. /* These two are for user programs to look at, when they are interested.  */
  196.  
  197. unsigned int malloc_sbrk_used;       /* amount of data space used now */
  198. unsigned int malloc_sbrk_unused;     /* amount more we can have */
  199.  
  200. /* start of data space; can be changed by calling init_malloc */
  201. static char *data_space_start;
  202.  
  203. #ifdef MSTATS
  204. static int nmalloc[30];
  205. static int nmal, nfre;
  206. #endif /* MSTATS */
  207.  
  208. /* If range checking is not turned on, all we have is a flag indicating
  209.    whether memory is allocated, an index in nextf[], and a size field; to
  210.    realloc() memory we copy either size bytes or 1<<(index+3) bytes depending
  211.    on whether the former can hold the exact size (given the value of
  212.    'index').  If range checking is on, we always need to know how much space
  213.    is allocated, so the 'size' field is never used. */
  214.  
  215. struct mhead {
  216.     char     mh_alloc;    /* ISALLOC or ISFREE */
  217.     char     mh_index;    /* index in nextf[] */
  218. /* Remainder are valid only when block is allocated */
  219.     unsigned short mh_size;    /* size, if < 0x10000 */
  220. #ifdef rcheck
  221.     unsigned mh_nbytes;    /* number of bytes allocated */
  222.     int      mh_magic4;    /* should be == MAGIC4 */
  223. #endif /* rcheck */
  224. };
  225.  
  226. /* Access free-list pointer of a block.
  227.   It is stored at block + 4.
  228.   This is not a field in the mhead structure
  229.   because we want sizeof (struct mhead)
  230.   to describe the overhead for when the block is in use,
  231.   and we do not want the free-list pointer to count in that.  */
  232.  
  233. #define CHAIN(a) \
  234.   (*(struct mhead **) (sizeof (char *) + (char *) (a)))
  235.  
  236. #ifdef rcheck
  237.  
  238. /* To implement range checking, we write magic values in at the beginning and
  239.    end of each allocated block, and make sure they are undisturbed whenever a
  240.    free or a realloc occurs. */
  241. /* Written in each of the 4 bytes following the block's real space */
  242. #define MAGIC1 0x55
  243. /* Written in the 4 bytes before the block's real space */
  244. #define MAGIC4 0x55555555
  245. #define ASSERT(p) if (!(p)) botch("p"); else
  246. #define EXTRA  4        /* 4 bytes extra for MAGIC1s */
  247. #else
  248. #define ASSERT(p)
  249. #define EXTRA  0
  250. #endif /* rcheck */
  251.  
  252.  
  253. /* nextf[i] is free list of blocks of size 2**(i + 3)  */
  254.  
  255. static struct mhead *nextf[30];
  256.  
  257. /* busy[i] is nonzero while allocation of block size i is in progress.  */
  258.  
  259. static char busy[30];
  260.  
  261. /* Number of bytes of writable memory we can expect to be able to get */
  262. static unsigned int lim_data;
  263.  
  264. /* Level number of warnings already issued.
  265.   0 -- no warnings issued.
  266.   1 -- 75% warning already issued.
  267.   2 -- 85% warning already issued.
  268. */
  269. static int warnlevel;
  270.  
  271. /* Function to call to issue a warning;
  272.    0 means don't issue them.  */
  273. static void (*warnfunction) ();
  274.  
  275. /* nonzero once initial bunch of free blocks made */
  276. static int gotpool;
  277.  
  278. char *_malloc_base;
  279.  
  280. static void getpool ();
  281.  
  282. /* Cause reinitialization based on job parameters;
  283.   also declare where the end of pure storage is. */
  284. void
  285. malloc_init (start, warnfun)
  286.      char *start;
  287.      void (*warnfun) ();
  288. {
  289.   if (start)
  290.     data_space_start = start;
  291.   lim_data = 0;
  292.   warnlevel = 0;
  293.   warnfunction = warnfun;
  294. }
  295.  
  296. /* Return the maximum size to which MEM can be realloc'd
  297.    without actually requiring copying.  */
  298.  
  299. int
  300. malloc_usable_size (mem)
  301.      char *mem;
  302. {
  303.   int blocksize = 8 << (((struct mhead *) mem) - 1) -> mh_index;
  304.  
  305.   return blocksize - sizeof (struct mhead) - EXTRA;
  306. }
  307.  
  308. static void
  309. morecore (nu)            /* ask system for more memory */
  310.      register int nu;        /* size index to get more of  */
  311. {
  312.   char *sbrk ();
  313.   register char *cp;
  314.   register int nblks;
  315.   register unsigned int siz;
  316.   int oldmask;
  317.  
  318. #ifdef BSD
  319. #ifndef BSD4_1
  320.   oldmask = sigsetmask (-1);
  321. #endif
  322. #endif
  323.  
  324.   if (!data_space_start)
  325.     {
  326.       data_space_start = start_of_data ();
  327.     }
  328.  
  329.   if (lim_data == 0)
  330.     get_lim_data ();
  331.  
  332.  /* On initial startup, get two blocks of each size up to 1k bytes */
  333.   if (!gotpool)
  334.     { getpool (); getpool (); gotpool = 1; }
  335.  
  336.   /* Find current end of memory and issue warning if getting near max */
  337.  
  338. #ifndef VMS
  339.   /* Maximum virtual memory on VMS is difficult to calculate since it
  340.    * depends on several dynmacially changing things. Also, alignment
  341.    * isn't that important. That is why much of the code here is ifdef'ed
  342.    * out for VMS systems.
  343.    */
  344.   cp = sbrk (0);
  345.   siz = cp - data_space_start;
  346.   malloc_sbrk_used = siz;
  347.   malloc_sbrk_unused = lim_data - siz;
  348.  
  349.   if (warnfunction)
  350.     switch (warnlevel)
  351.       {
  352.       case 0: 
  353.     if (siz > (lim_data / 4) * 3)
  354.       {
  355.         warnlevel++;
  356.         (*warnfunction) ("Warning: past 75% of memory limit");
  357.       }
  358.     break;
  359.       case 1: 
  360.     if (siz > (lim_data / 20) * 17)
  361.       {
  362.         warnlevel++;
  363.         (*warnfunction) ("Warning: past 85% of memory limit");
  364.       }
  365.     break;
  366.       case 2: 
  367.     if (siz > (lim_data / 20) * 19)
  368.       {
  369.         warnlevel++;
  370.         (*warnfunction) ("Warning: past 95% of memory limit");
  371.       }
  372.     break;
  373.       }
  374.  
  375.   if ((int) cp & 0x3ff)    /* land on 1K boundaries */
  376.     sbrk (1024 - ((int) cp & 0x3ff));
  377. #endif /* not VMS */
  378.  
  379.  /* Take at least 2k, and figure out how many blocks of the desired size
  380.     we're about to get */
  381.   nblks = 1;
  382.   if ((siz = nu) < 8)
  383.     nblks = 1 << ((siz = 8) - nu);
  384.  
  385.   if ((cp = sbrk (1 << (siz + 3))) == (char *) -1)
  386.     return;            /* no more room! */
  387. #ifndef VMS
  388.   if ((int) cp & 7)
  389.     {        /* shouldn't happen, but just in case */
  390.       cp = (char *) (((int) cp + 8) & ~7);
  391.       nblks--;
  392.     }
  393. #endif /* not VMS */
  394.  
  395.  /* save new header and link the nblks blocks together */
  396.   nextf[nu] = (struct mhead *) cp;
  397.   siz = 1 << (nu + 3);
  398.   while (1)
  399.     {
  400.       ((struct mhead *) cp) -> mh_alloc = ISFREE;
  401.       ((struct mhead *) cp) -> mh_index = nu;
  402.       if (--nblks <= 0) break;
  403.       CHAIN ((struct mhead *) cp) = (struct mhead *) (cp + siz);
  404.       cp += siz;
  405.     }
  406.   CHAIN ((struct mhead *) cp) = 0;
  407.  
  408. #ifdef BSD
  409. #ifndef BSD4_1
  410.   sigsetmask (oldmask);
  411. #endif
  412. #endif
  413. }
  414.  
  415. static void
  416. getpool ()
  417. {
  418.   register int nu;
  419.   char * sbrk ();
  420.   register char *cp = sbrk (0);
  421.  
  422.   if ((int) cp & 0x3ff)    /* land on 1K boundaries */
  423.     sbrk (1024 - ((int) cp & 0x3ff));
  424.  
  425.   /* Record address of start of space allocated by malloc.  */
  426.   if (_malloc_base == 0)
  427.     _malloc_base = cp;
  428.  
  429.   /* Get 2k of storage */
  430.  
  431.   cp = sbrk (04000);
  432.   if (cp == (char *) -1)
  433.     return;
  434.  
  435.   /* Divide it into an initial 8-word block
  436.      plus one block of size 2**nu for nu = 3 ... 10.  */
  437.  
  438.   CHAIN (cp) = nextf[0];
  439.   nextf[0] = (struct mhead *) cp;
  440.   ((struct mhead *) cp) -> mh_alloc = ISFREE;
  441.   ((struct mhead *) cp) -> mh_index = 0;
  442.   cp += 8;
  443.  
  444.   for (nu = 0; nu < 7; nu++)
  445.     {
  446.       CHAIN (cp) = nextf[nu];
  447.       nextf[nu] = (struct mhead *) cp;
  448.       ((struct mhead *) cp) -> mh_alloc = ISFREE;
  449.       ((struct mhead *) cp) -> mh_index = nu;
  450.       cp += 8 << nu;
  451.     }
  452. }
  453.  
  454. char *
  455. malloc (n)        /* get a block */
  456.      unsigned n;
  457. {
  458.   register struct mhead *p;
  459.   register unsigned int nbytes;
  460.   register int nunits = 0;
  461.  
  462.   /* Figure out how many bytes are required, rounding up to the nearest
  463.      multiple of 4, then figure out which nextf[] area to use */
  464.   nbytes = (n + sizeof *p + EXTRA + 3) & ~3;
  465.   {
  466.     register unsigned int   shiftr = (nbytes - 1) >> 2;
  467.  
  468.     while (shiftr >>= 1)
  469.       nunits++;
  470.   }
  471.  
  472.   /* In case this is reentrant use of malloc from signal handler,
  473.      pick a block size that no other malloc level is currently
  474.      trying to allocate.  That's the easiest harmless way not to
  475.      interfere with the other level of execution.  */
  476.   while (busy[nunits]) nunits++;
  477.   busy[nunits] = 1;
  478.  
  479.   /* If there are no blocks of the appropriate size, go get some */
  480.   /* COULD SPLIT UP A LARGER BLOCK HERE ... ACT */
  481.   if (nextf[nunits] == 0)
  482.     morecore (nunits);
  483.  
  484.   /* Get one block off the list, and set the new list head */
  485.   if ((p = nextf[nunits]) == 0)
  486.     {
  487.       busy[nunits] = 0;
  488.       return 0;
  489.     }
  490.   nextf[nunits] = CHAIN (p);
  491.   busy[nunits] = 0;
  492.  
  493.   /* Check for free block clobbered */
  494.   /* If not for this check, we would gobble a clobbered free chain ptr */
  495.   /* and bomb out on the NEXT allocate of this size block */
  496.   if (p -> mh_alloc != ISFREE || p -> mh_index != nunits)
  497. #ifdef rcheck
  498.     botch ("block on free list clobbered");
  499. #else /* not rcheck */
  500.     abort ();
  501. #endif /* not rcheck */
  502.  
  503.   /* Fill in the info, and if range checking, set up the magic numbers */
  504.   p -> mh_alloc = ISALLOC;
  505. #ifdef rcheck
  506.   p -> mh_nbytes = n;
  507.   p -> mh_magic4 = MAGIC4;
  508.   {
  509.     register char  *m = (char *) (p + 1) + n;
  510.  
  511.     *m++ = MAGIC1, *m++ = MAGIC1, *m++ = MAGIC1, *m = MAGIC1;
  512.   }
  513. #else /* not rcheck */
  514.   p -> mh_size = n;
  515. #endif /* not rcheck */
  516. #ifdef MSTATS
  517.   nmalloc[nunits]++;
  518.   nmal++;
  519. #endif /* MSTATS */
  520.   return (char *) (p + 1);
  521. }
  522.  
  523. free (mem)
  524.      char *mem;
  525. {
  526.   register struct mhead *p;
  527.   {
  528.     register char *ap = mem;
  529.  
  530.     if (ap == 0)
  531.       return;
  532.  
  533.     p = (struct mhead *) ap - 1;
  534.     if (p -> mh_alloc == ISMEMALIGN)
  535.       {
  536.     ap -= p->mh_size;
  537.     p = (struct mhead *) ap - 1;
  538.       }
  539.  
  540.     if (p -> mh_alloc != ISALLOC)
  541.       abort ();
  542.  
  543. #ifdef rcheck
  544.     ASSERT (p -> mh_magic4 == MAGIC4);
  545.     ap += p -> mh_nbytes;
  546.     ASSERT (*ap++ == MAGIC1); ASSERT (*ap++ == MAGIC1);
  547.     ASSERT (*ap++ == MAGIC1); ASSERT (*ap   == MAGIC1);
  548. #endif /* rcheck */
  549.   }
  550.   {
  551.     register int nunits = p -> mh_index;
  552.  
  553.     ASSERT (nunits <= 29);
  554.     p -> mh_alloc = ISFREE;
  555.  
  556.     /* Protect against signal handlers calling malloc.  */
  557.     busy[nunits] = 1;
  558.     /* Put this block on the free list.  */
  559.     CHAIN (p) = nextf[nunits];
  560.     nextf[nunits] = p;
  561.     busy[nunits] = 0;
  562.  
  563. #ifdef MSTATS
  564.     nmalloc[nunits]--;
  565.     nfre++;
  566. #endif /* MSTATS */
  567.   }
  568. }
  569.  
  570. char *
  571. realloc (mem, n)
  572.      char *mem;
  573.      register unsigned n;
  574. {
  575.   register struct mhead *p;
  576.   register unsigned int tocopy;
  577.   register unsigned int nbytes;
  578.   register int nunits;
  579.  
  580.   if ((p = (struct mhead *) mem) == 0)
  581.     return malloc (n);
  582.   p--;
  583.   nunits = p -> mh_index;
  584.   ASSERT (p -> mh_alloc == ISALLOC);
  585. #ifdef rcheck
  586.   ASSERT (p -> mh_magic4 == MAGIC4);
  587.   {
  588.     register char *m = mem + (tocopy = p -> mh_nbytes);
  589.     ASSERT (*m++ == MAGIC1); ASSERT (*m++ == MAGIC1);
  590.     ASSERT (*m++ == MAGIC1); ASSERT (*m   == MAGIC1);
  591.   }
  592. #else /* not rcheck */
  593.   if (p -> mh_index >= 13)
  594.     tocopy = (1 << (p -> mh_index + 3)) - sizeof *p;
  595.   else
  596.     tocopy = p -> mh_size;
  597. #endif /* not rcheck */
  598.  
  599.   /* See if desired size rounds to same power of 2 as actual size. */
  600.   nbytes = (n + sizeof *p + EXTRA + 7) & ~7;
  601.  
  602.   /* If ok, use the same block, just marking its size as changed.  */
  603.   if (nbytes > (4 << nunits) && nbytes <= (8 << nunits))
  604.     {
  605. #ifdef rcheck
  606.       register char *m = mem + tocopy;
  607.       *m++ = 0;  *m++ = 0;  *m++ = 0;  *m++ = 0;
  608.       p-> mh_nbytes = n;
  609.       m = mem + n;
  610.       *m++ = MAGIC1;  *m++ = MAGIC1;  *m++ = MAGIC1;  *m++ = MAGIC1;
  611. #else /* not rcheck */
  612.       p -> mh_size = n;
  613. #endif /* not rcheck */
  614.       return mem;
  615.     }
  616.  
  617.   if (n < tocopy)
  618.     tocopy = n;
  619.   {
  620.     register char *new;
  621.  
  622.     if ((new = malloc (n)) == 0)
  623.       return 0;
  624.     bcopy (mem, new, tocopy);
  625.     free (mem);
  626.     return new;
  627.   }
  628. }
  629.  
  630. #ifndef VMS
  631.  
  632. char *
  633. memalign (alignment, size)
  634.      unsigned alignment, size;
  635. {
  636.   register char *ptr = malloc (size + alignment);
  637.   register char *aligned;
  638.   register struct mhead *p;
  639.  
  640.   if (ptr == 0)
  641.     return 0;
  642.   /* If entire block has the desired alignment, just accept it.  */
  643.   if (((int) ptr & (alignment - 1)) == 0)
  644.     return ptr;
  645.   /* Otherwise, get address of byte in the block that has that alignment.  */
  646.   aligned = (char *) (((int) ptr + alignment - 1) & -alignment);
  647.  
  648.   /* Store a suitable indication of how to free the block,
  649.      so that free can find the true beginning of it.  */
  650.   p = (struct mhead *) aligned - 1;
  651.   p -> mh_size = aligned - ptr;
  652.   p -> mh_alloc = ISMEMALIGN;
  653.   return aligned;
  654. }
  655.  
  656. #ifndef HPUX
  657. /* This runs into trouble with getpagesize on HPUX.
  658.    Patching out seems cleaner than the ugly fix needed.  */
  659. char *
  660. valloc (size)
  661. {
  662.   return memalign (getpagesize (), size);
  663. }
  664. #endif /* not HPUX */
  665. #endif /* not VMS */
  666.  
  667. #ifdef MSTATS
  668. /* Return statistics describing allocation of blocks of size 2**n. */
  669.  
  670. struct mstats_value
  671.   {
  672.     int blocksize;
  673.     int nfree;
  674.     int nused;
  675.   };
  676.  
  677. struct mstats_value
  678. malloc_stats (size)
  679.      int size;
  680. {
  681.   struct mstats_value v;
  682.   register int i;
  683.   register struct mhead *p;
  684.  
  685.   v.nfree = 0;
  686.  
  687.   if (size < 0 || size >= 30)
  688.     {
  689.       v.blocksize = 0;
  690.       v.nused = 0;
  691.       return v;
  692.     }
  693.  
  694.   v.blocksize = 1 << (size + 3);
  695.   v.nused = nmalloc[size];
  696.  
  697.   for (p = nextf[size]; p; p = CHAIN (p))
  698.     v.nfree++;
  699.  
  700.   return v;
  701. }
  702. #endif /* MSTATS */
  703.  
  704. /*
  705.  *    This function returns the total number of bytes that the process
  706.  *    will be allowed to allocate via the sbrk(2) system call.  On
  707.  *    BSD systems this is the total space allocatable to stack and
  708.  *    data.  On USG systems this is the data space only.
  709.  */
  710.  
  711. #ifdef USG
  712.  
  713. get_lim_data ()
  714. {
  715.   extern long ulimit ();
  716.     
  717.   lim_data = ulimit (3, 0);
  718.   lim_data -= (long) data_space_start;
  719. }
  720.  
  721. #else /* not USG */
  722. #ifndef BSD42
  723.  
  724. get_lim_data ()
  725. {
  726.   lim_data = vlimit (LIM_DATA, -1);
  727. }
  728.  
  729. #else /* BSD42 */
  730.  
  731. get_lim_data ()
  732. {
  733.   struct rlimit XXrlimit;
  734.  
  735.   getrlimit (RLIMIT_DATA, &XXrlimit);
  736. #ifdef RLIM_INFINITY
  737.   lim_data = XXrlimit.rlim_cur & RLIM_INFINITY; /* soft limit */
  738. #else
  739.   lim_data = XXrlimit.rlim_cur;    /* soft limit */
  740. #endif
  741. }
  742.  
  743. #endif /* BSD42 */
  744. #endif /* not USG */
  745.  
  746. #ifdef VMS
  747. /* There is a problem when dumping and restoring things on VMS. Calls
  748.  * to SBRK don't necessarily result in contiguous allocation. Dumping
  749.  * doesn't work when it isn't. Therefore, we make the initial
  750.  * allocation contiguous by allocating a big chunk, and do SBRKs from
  751.  * there. Once Emacs has dumped there is no reason to continue
  752.  * contiguous allocation, malloc doesn't depend on it.
  753.  *
  754.  * There is a further problem of using brk and sbrk while using VMS C
  755.  * run time library routines malloc, calloc, etc. The documentation
  756.  * says that this is a no-no, although I'm not sure why this would be
  757.  * a problem. In any case, we remove the necessity to call brk and
  758.  * sbrk, by calling calloc (to assure zero filled data) rather than
  759.  * sbrk.
  760.  *
  761.  * VMS_ALLOCATION_SIZE is the size of the allocation array. This
  762.  * should be larger than the malloc size before dumping. Making this
  763.  * too large will result in the startup procedure slowing down since
  764.  * it will require more space and time to map it in.
  765.  *
  766.  * The value for VMS_ALLOCATION_SIZE in the following define was determined
  767.  * by running emacs linked (and a large allocation) with the debugger and
  768.  * looking to see how much storage was used. The allocation was 201 pages,
  769.  * so I rounded it up to a power of two.
  770.  */
  771. #ifndef VMS_ALLOCATION_SIZE
  772. #define VMS_ALLOCATION_SIZE    (512*256)
  773. #endif
  774.  
  775. /* Use VMS RTL definitions */
  776. #undef sbrk
  777. #undef brk
  778. #undef malloc
  779. int vms_out_initial = 0;
  780. char vms_initial_buffer[VMS_ALLOCATION_SIZE];
  781. static char *vms_current_brk = &vms_initial_buffer;
  782. static char *vms_end_brk = &vms_initial_buffer[VMS_ALLOCATION_SIZE-1];
  783.  
  784. #include <stdio.h>
  785.  
  786. char *
  787. sys_sbrk (incr)
  788.      int incr;
  789. {
  790.   char *sbrk(), *temp, *ptr;
  791.  
  792.   if (vms_out_initial)
  793.     {
  794.       /* out of initial allocation... */
  795.       if (!(temp = malloc (incr)))
  796.     temp = (char *) -1;
  797.     }
  798.   else
  799.     {
  800.       /* otherwise, go out of our area */
  801.       ptr = vms_current_brk + incr; /* new current_brk */
  802.       if (ptr <= vms_end_brk)
  803.     {
  804.       temp = vms_current_brk;
  805.       vms_current_brk = ptr;
  806.     }
  807.       else
  808.     {
  809.       vms_out_initial = 1;    /* mark as out of initial allocation */
  810.       if (!(temp = malloc (incr)))
  811.         temp = (char *) -1;
  812.     }
  813.     }
  814.   return temp;
  815. }
  816. #endif /* VMS */
  817.